package com.zuokun.service.impl;

import com.zuokun.manager.PlayerManager;
import com.zuokun.mapper.LoginMapper;
import com.zuokun.protol.login.MsgGetAchieve;
import com.zuokun.protol.login.MsgLogin;
import com.zuokun.protol.login.MsgRegister;
import com.zuokun.service.LoginService;
import com.zuokun.vo.PlayerInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Override
    public MsgLogin login(MsgLogin msgLogin) {
        String username = msgLogin.getUsername();
        String password = msgLogin.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        MsgLogin accountInfo = loginMapper.getUserById(username);
        if (accountInfo == null) {
            accountInfo = new MsgLogin();
            accountInfo.setUsername(username);
            accountInfo.setPassword(password);
            accountInfo.setMessage("用户名不存在");
            accountInfo.setResult(false);
        } else {
            if (accountInfo.getPassword().equals(password)) {
                accountInfo.setResult(true);
                PlayerInfo playerInfo = loginMapper.getPlayerInfoById(accountInfo.getId());
                PlayerManager.playerMap.put(msgLogin.getCtx(), playerInfo);
            } else {
                accountInfo.setMessage("密码不正确");
                accountInfo.setResult(false);
            }
        }
        return accountInfo;
    }

    /**
     * 获取玩家信息
     *
     * @param msgGetAchieve
     * @return
     */
    @Override
    public MsgGetAchieve getPlayerInfo(MsgGetAchieve msgGetAchieve) {
        MsgGetAchieve result = new MsgGetAchieve();
        if (msgGetAchieve.getId() == null) {
            log.error("getPlayerInfo：玩家id为空");
        } else {
            PlayerInfo playerInfo = loginMapper.getPlayerInfoById(msgGetAchieve.getId());
            result.setBeanCount(playerInfo.getBeanCount());
        }

        return result;
    }

    /**
     * 注册
     *
     * @param msgRegister
     * @return
     */
    @Override
    public MsgRegister register(MsgRegister msgRegister) {
        MsgLogin user = loginMapper.getUserById(msgRegister.getUsername());
        if (user != null) {
            msgRegister.setMessage("用户名：" + msgRegister.getUsername() + " 已存在！");
            msgRegister.setResult(false);
        } else {
            msgRegister.setPassword(DigestUtils.md5DigestAsHex(msgRegister.getPassword().getBytes()));
            loginMapper.addAccount(msgRegister);
            PlayerInfo playerInfo = new PlayerInfo(msgRegister.getId(), 100);
            loginMapper.addPlayerInfo(playerInfo);
            msgRegister.setResult(true);
            msgRegister.setMessage("注册成功！");
        }
        return msgRegister;
    }
}
